﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Globalization;
using POSSystem.BLL;

namespace MobileShop.Controls
{
    public delegate void CartChangedEventHandler(object sender, EventArgs e);
    public partial class ShoppingCart : BaseRepeater
    {
        public event CartChangedEventHandler CartChanged;
        private void OnCartChanged(EventArgs e)
        {
            if (CartChanged != null)
                CartChanged(this, e);
        }

        public bool EnablePayPal
        {
            get { if (ViewState[ClientID + "EnablePayPal"] == null) ViewState[ClientID + "EnablePayPal"] = false; return (bool)ViewState[ClientID + "EnablePayPal"]; }
            set { ViewState[ClientID + "EnablePayPal"] = value; }
        }

        protected void rpt_OnNeedDataSource(object sender, EventArgs e)
        {
            rpt.DataSource = BasePage.SelectedItems.DefaultView;
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            btnBuy.PostBackUrl = this.ResolveUrl("~/Checkout.aspx");
            if (!IsPostBack)
            {
                Refresh();
            }
        }

        public Decimal TotalAmt
        {
            get
            {
                if (ViewState[ClientID + "_TotalAmt"] == null || !(ViewState[ClientID + "_TotalAmt"] is Decimal))
                    ViewState[ClientID + "_TotalAmt"] = (Decimal)0;
                return Decimal.Parse(ViewState[ClientID + "_TotalAmt"].ToString(), CultureInfo.InvariantCulture);
            }
            set { ViewState[ClientID + "_TotalAmt"] = value; }
        }

        public Decimal TotalGST
        {
            get
            {
                if (ViewState[ClientID + "_TotalGST"] == null || !(ViewState[ClientID + "_TotalGST"] is Decimal))
                    ViewState[ClientID + "_TotalGST"] = 0;
                return Decimal.Parse(ViewState[ClientID + "_TotalGST"].ToString(), CultureInfo.InvariantCulture);
            }
            set { ViewState[ClientID + "_TotalGST"] = value; }
        }

        protected void rpt_OnItemDataBound(object sender, DataGridItemEventArgs e)
        {
            if (e.Item.ItemType == ListItemType.Footer)
            {
                e.Item.Cells[0].Text = BasePage.SelectedItems.RowCount > 0 ? string.Format("{0} Item(s)", BasePage.SelectedItems.RowCount) : "No item(s) to display.";
                e.Item.Cells[3].Text = string.Format("{0:C}", TotalGST);
                e.Item.Cells[4].Text = string.Format("{0:C}", TotalAmt);
                e.Item.Cells[3].Attributes.Add("align", "right");
                e.Item.Cells[4].Attributes.Add("align", "right");
            }
            else
            {
                TextBox txt = (TextBox)e.Item.FindControl("txtQuantity");
                Label lbl = (Label)e.Item.FindControl("lblQuantity");
                if (txt != null)
                    txt.Visible = !ReadOnly;
                if (lbl != null)
                    lbl.Visible = ReadOnly;
            }
        }

        public void UpdateTotalAmt()
        {
            TotalGST = 0;
            TotalAmt = 0;

            string oldFilter = BasePage.SelectedItems.Filter;

            if (BasePage.SelectedItems != null && BasePage.SelectedItems.RowCount > 0 && !BasePage.SelectedItems.IsColumnNull(POSSystem.BLL.OrderItems.ColumnNames.GST) && !BasePage.SelectedItems.IsColumnNull(POSSystem.BLL.OrderItems.ColumnNames.TotalAmount))
            {
                BasePage.SelectedItems.Rewind();
                for (int i = 0; i < BasePage.SelectedItems.RowCount; i++)
                {
                    TotalAmt += (decimal)BasePage.SelectedItems.GetColumn(POSSystem.BLL.OrderItems.ColumnNames.TotalAmount);
                    TotalGST += (decimal)BasePage.SelectedItems.GetColumn(POSSystem.BLL.OrderItems.ColumnNames.GST);
                    BasePage.SelectedItems.MoveNext();
                }
            }

            BasePage.SelectedItems.Filter = oldFilter;
        }

        public decimal DiscountAmount
        {
            get
            {
                if (ViewState[ClientID + "_DiscountAmount"] == null || !(ViewState[ClientID + "_DiscountAmount"] is Decimal))
                    ViewState[ClientID + "_DiscountAmount"] = 0;
                return Decimal.Parse(ViewState[ClientID + "_DiscountAmount"].ToString(), CultureInfo.InvariantCulture);
            }
            set
            {
                ViewState[ClientID + "_DiscountAmount"] = value;
            }
        }

        decimal TmpDiscountAmount
        {
            get;
            set;
        }

        public void Refresh()
        {
            UpdateTotalAmt();
            TmpDiscountAmount = DiscountAmount;

            Rebind();
            lblNoItems.Visible = BasePage.SelectedItems == null || BasePage.SelectedItems.RowCount == 0;
            btnUpdate.Visible = BasePage.SelectedItems != null && BasePage.SelectedItems.RowCount > 0;
            btnBuy.Visible = btnUpdate.Visible;
        }

        public bool ReadOnly
        {
            get { return ViewState[ClientID + "ReadOnly"] != null ? (bool)ViewState[ClientID + "ReadOnly"] : false; }
            set { ViewState[ClientID + "ReadOnly"] = value;}
        }

        public decimal GetPrice(decimal amt, int qty)
        {
            decimal total = amt * qty;
            decimal res = Math.Max(0, total - TmpDiscountAmount); ;
            if (TmpDiscountAmount > total)
                TmpDiscountAmount -= total;
            else
                TmpDiscountAmount = 0;

            return Math.Round(res / qty, 2);
        }

        protected void lnkDelete_OnClick(object sender, EventArgs e)
        {
            string oldFilter = BasePage.SelectedItems.Filter;
            LinkButton lnk = (LinkButton)sender;

            try
            {
                BasePage.SelectedItems.Filter = POSSystem.BLL.OrderItems.ColumnNames.ProductID + "=" + lnk.Attributes["ItemID"];

                if (BasePage.SelectedItems.RowCount > 0)
                    BasePage.SelectedItems.MarkAsDeleted();

                BasePage.SelectedItems.Filter = oldFilter;

                Refresh();
                OnCartChanged(e);
            }
            catch (Exception ex)
            {
                BasePage.SelectedItems.Filter = oldFilter;
                ErrorLog.WriteToFile("ShoppingCart.ascx.cs", "btnDelete_OnClick", ex.StackTrace);
            }
        }

        protected void btnUpdate_OnClick(object sender, EventArgs e)
        {
            BasePage.SelectedItems.Rewind();
            for (int i = 0; i < rpt.Items.Count; i++)
            {
                TextBox txt = (TextBox)rpt.Items[i].FindControl("txtQuantity");
                int productID = int.Parse(txt.Attributes["ItemID"]);
                int qty = int.Parse(txt.Text);

                BasePage.SelectedItems.Filter = POSSystem.BLL.OrderItems.ColumnNames.ProductID + "=" + txt.Attributes["ItemID"];

                if (BasePage.SelectedItems.RowCount > 0)
                {
                    if (BasePage.SelectedItems.Quantity != qty)
                    {
                        BasePage.SelectedItems.Quantity = qty;
                        BasePage.SelectedItems.TotalAmount = BasePage.SelectedItems.Quantity * BasePage.SelectedItems.CustomerPrice;
                        if (BasePage.SelectedItems.GST > 0)
                            BasePage.SelectedItems.GST = Math.Round(BasePage.SelectedItems.TotalAmount * SysVars.GST / (SysVars.GST + 100), 2);
                    }
                }
            }
            OnCartChanged(e);
            BasePage.SelectedItems.Filter = "";
            BasePage.SelectedItems.Rewind();
            Refresh();
        }
    }
}